package com.pj.compose.ui.page.other.bluetooth

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.pj.compose.R
import com.pj.compose.ui.compose.AppTopBarColumn
import com.pj.compose.viewmodel.BluetoothViewModel

@Composable
fun BluetoothHidPage(
    modifier: Modifier = Modifier,
    vm: BluetoothViewModel,
    onStart: () -> Unit,
    onScan: () -> Unit,
    onHid: () -> Unit,
    onFoundItemClick: (device: BluetoothDevice) -> Unit,
) {
    AppTopBarColumn(
        modifier = modifier,
        title = stringResource(id = R.string.bluetooth_hid),
        backClick = { ActivityUtils.getTopActivity().onBackPressed() }) {
        TopButtons(
            isBluetoothEnabled = vm.isBluetoothEnabled,
            startClick = onStart,
            scanClick = {
                vm.contentType = 0
                onScan()
            },
            hidClick = {
                       vm.contentType = 1
            },
        )
        BluetoothContent(vm = vm, onFoundItemClick = onFoundItemClick)
    }
}

/**
 * 功能按键
 */
@Composable
private fun TopButtons(
    isBluetoothEnabled: Boolean,
    startClick: () -> Unit,
    scanClick: () -> Unit,
    hidClick: () -> Unit,
) {
    Row(Modifier.padding(15.dp), horizontalArrangement = Arrangement.spacedBy(15.dp)) {
        if (!isBluetoothEnabled)
            TopButton(onClick = startClick, text = "启动蓝牙")
        else {
            TopButton(onClick = scanClick, text = "扫描设备")
        }
        TopButton(onClick = hidClick, text = "键盘设备")
    }
}

/**
 * 内容部分
 */
@Composable
private fun BluetoothContent(
    vm: BluetoothViewModel,
    onFoundItemClick: (device: BluetoothDevice) -> Unit,
) {
    if (vm.contentType == 0)
        BluetoothDeviceList(vm = vm, onFoundItemClick = onFoundItemClick)
    else if (vm.contentType == 1){
        BluetoothHidContent()
    }
}

@Composable
private fun BluetoothDeviceList(
    vm: BluetoothViewModel,
    onFoundItemClick: (device: BluetoothDevice) -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .verticalScroll(rememberScrollState())
            .background(color = Color.White)
    ) {
        Text(
            text = "已配对的设备", modifier = Modifier
                .fillMaxWidth()
                .padding(15.dp)
        )
        Divider()
        vm.boundDevices.forEach {
            BluetoothDeviceItem(device = it, onClick = {})
            Divider()
        }
        Text(
            text = "可用的设备", modifier = Modifier
                .fillMaxWidth()
                .padding(15.dp)
        )
        Divider()
        vm.foundDevices.forEach {
            BluetoothDeviceItem(device = it, onClick = { onFoundItemClick(it) })
            Divider()
        }
    }
}


@SuppressLint("MissingPermission")
@Composable
private fun BluetoothDeviceItem(device: BluetoothDevice, onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(15.dp)
            .clickable(onClick = onClick)
    ) {
        Text(text = if (device.name.isNullOrEmpty()) device.address else device.name)
    }
}

@Composable
private fun BluetoothHidContent() {
    Column {
        MouseContent(modifier = Modifier.weight(1f))
        Divider()
        KeyBoardContent(
            modifier = Modifier
                .padding(15.dp)
        )
    }
}

/**
 * 鼠标
 */
@Composable
private fun MouseContent(
    modifier: Modifier = Modifier,
    onLeftClick: () -> Unit = {},
    onRightClick: () -> Unit = { },
) {
    Column(modifier = modifier) {
        Divider()
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(80.dp)
        ) {
            Box(modifier = Modifier
                .weight(1f)
                .fillMaxHeight()
                .clickable { onLeftClick() })
            Divider(
                modifier = Modifier
                    .width(1.dp)
                    .fillMaxHeight()
            )
            Box(modifier = Modifier
                .width(50.dp)
                .fillMaxHeight()
                .clickable { })
            Divider(
                modifier = Modifier
                    .width(1.dp)
                    .fillMaxHeight()
            )
            Box(modifier = Modifier
                .weight(1f)
                .fillMaxHeight()
                .clickable { onRightClick() })
        }
        Divider()
        Box(modifier = Modifier
            .fillMaxWidth()
            .weight(1f)
            .background(color = Color.LightGray)
            .pointerInput(Unit) {
                detectDragGestures { change, dragAmount ->
                    LogUtils.e("change : ${change.position},dragAmount : ${dragAmount.x} , ${dragAmount.y}")
                }
            })
    }
}

/**
 * 键盘
 */
@Composable
private fun KeyBoardContent(modifier: Modifier = Modifier) {
    val line1 = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "0")
    val line2 = listOf("Q", "W", "E", "R", "T", "Y", "U", "I", "O", "Q")
    val line3 = listOf("A", "S", "D", "F", "G", "H", "J", "K", "L")
    val line4 = listOf("Z", "X", "C", "V", "B", "N", "M")
    val rowWidth = LocalConfiguration.current.screenWidthDp - 30
    val keyButtonWidth = ((rowWidth - line1.lastIndex * 5) / line1.size).dp

    Column(
        modifier = modifier,
        verticalArrangement = Arrangement.spacedBy(5.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        KeyBoardButtonRow(
            modifier = Modifier.fillMaxWidth(),
            buttonWidth = keyButtonWidth,
            list = line1
        )
        KeyBoardButtonRow(
            modifier = Modifier.fillMaxWidth(),
            buttonWidth = keyButtonWidth,
            list = line2
        )
        KeyBoardButtonRow(
            list = line3,
            buttonWidth = keyButtonWidth,
            modifier = Modifier
                .fillMaxWidth()
        )
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(5.dp)
        ) {
            KeyBoardButton(
                onClick = { },
                modifier = Modifier.weight(1f),
                text = "Shift",
                bgColor = Color.LightGray
            )
            KeyBoardButtonRow(list = line4, buttonWidth = keyButtonWidth)
            KeyBoardButton(
                onClick = { },
                modifier = Modifier.weight(1f),
                text = "Back",
                bgColor = Color.LightGray
            )
        }

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(5.dp)
        ) {
            KeyBoardButton(
                onClick = { },
                modifier = Modifier.defaultMinSize(minWidth = 50.dp),
                text = "Alt",
                bgColor = Color.LightGray
            )
            KeyBoardButton(
                onClick = { },
                modifier = Modifier.defaultMinSize(minWidth = 50.dp),
                text = "Win",
                bgColor = Color.LightGray
            )
            KeyBoardButton(
                onClick = { },
                modifier = Modifier.weight(1f),
                text = "  ",
                bgColor = Color.White
            )
            KeyBoardButton(
                onClick = { },
                modifier = Modifier.defaultMinSize(minWidth = 50.dp),
                text = "Menu",
                bgColor = Color.LightGray
            )
            KeyBoardButton(
                onClick = { },
                modifier = Modifier.defaultMinSize(minWidth = 50.dp),
                text = "Ctrl",
                bgColor = Color.LightGray
            )
        }
    }
}

/**
 * 字符类型的按钮
 */
@Composable
private fun KeyBoardButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    text: String,
    bgColor: Color,
    textColor: Color = Color.Black,
) {
    Button(
        onClick = onClick,
        modifier = modifier,
        shape = RoundedCornerShape(5.dp),
        elevation = ButtonDefaults.buttonElevation(defaultElevation = 2.dp),
        contentPadding = PaddingValues(),
        colors = ButtonDefaults.buttonColors(containerColor = bgColor, contentColor = textColor)
    ) {
        Text(text = text, fontSize = 13.sp, maxLines = 1)
    }
}

@Composable
private fun KeyBoardButtonRow(modifier: Modifier = Modifier, buttonWidth: Dp, list: List<String>) {
    Row(modifier = modifier, horizontalArrangement = Arrangement.spacedBy(5.dp)) {
        list.forEach { text ->
            KeyBoardButton(
                onClick = { },
                modifier = Modifier.width(buttonWidth),
                text = text,
                bgColor = Color.White
            )
        }
    }
}

@Composable
private fun TopButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    text: String,
) {
    Button(
        onClick = onClick,
        modifier = modifier,
        enabled = enabled,
        shape = RoundedCornerShape(5.dp),
        colors = ButtonDefaults.buttonColors()
    ) {
        Text(text = text, color = MaterialTheme.colors.onPrimary, fontSize = 13.sp)
    }
}